package com.example.children.config;


import com.example.children.Util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Key;
import java.security.SignatureException;
import java.util.Date;

@WebFilter("/*")  // 这个过滤器会应用于所有请求
public class AuthorizationFilter implements Filter  {

    private static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("AuthorizationFilter-init");
        // 初始化代码，如果需要的话
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        System.out.println("AuthorizationFilter-doFilter");

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String uri = httpRequest.getRequestURI();

        // 判断请求的 URI 是否是登录或注册相关的接口
        if (uri.contains("/login") || uri.contains("/register")) {
            System.out.println("可放行端口：如登录,注册等等");
            // 登录和注册接口不需要鉴权，直接放行
            chain.doFilter(request, response);
        }else {
            String authorizationHeader = httpRequest.getHeader("Authorization");

            // 检查 Authorization header 是否存在且以 "Bearer " 开头
            if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                String token = authorizationHeader.substring(7);  // 提取 Bearer 后的 Token
                // 验证 token
                if (JwtUtil.validateToken(token)) {
                    // 如果验证通过，继续执行请求链
                    chain.doFilter(request, response);
                } else {
                    // 如果 token 验证失败，设置状态码为 401 Unauthorized，并返回错误信息
                    sendUnauthorizedResponse(httpResponse, "令牌无效");
                }
            } else {
                // 如果缺少 Authorization header，返回 401 Unauthorized
                sendUnauthorizedResponse(httpResponse, "缺少 Authorization 标头");
            }
        }
    }





    // 可选：解析出 Token 中的用户信息（如果有的话）
    public static String getUserFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();  // 假设用户名或者用户ID存储在subject字段中
    }

    private void sendUnauthorizedResponse(HttpServletResponse response, String message) throws IOException {
        // 设置状态码为 401 Unauthorized
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // 设置响应内容类型为 JSON（你也可以根据需要使用纯文本）
        response.setContentType("application/json");
        // 输出详细的错误信息
        String jsonResponse = "{\"error\": \"Unauthorized\", \"message\": \"" + message + "\"}";
        response.getWriter().write(jsonResponse);
    }

    @Override
    public void destroy() {
        System.out.println("AuthorizationFilter-destroy");
        // 销毁代码，如果需要的话
    }



}

